/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-06-22 17:34:53
 * @LastEditTime: 2024-07-06 21:15:37
 * @FilePath: /nest_study/server/src/modules/system/dept/dept.service.ts
 */
import { Injectable } from '@nestjs/common';
import { CreateDeptDto, DeleteDeptDto, QueryDeptDto, UpdateDeptDto } from './dto/index.dto';
import { SystemDeptEntity } from './entities/dept.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { ResultData } from 'src/common/utils/result';
import { ListToTree } from 'src/common/utils';
import { SystemUserEntity } from '../user/entities/user.entity';

@Injectable()
export class DeptService {
  constructor(
    @InjectRepository(SystemDeptEntity)
    private readonly deptRepo: Repository<SystemDeptEntity>,
    @InjectRepository(SystemUserEntity)
    private readonly userRepo: Repository<SystemUserEntity>
  ) { }

  //查询列表
  async findTree(query: QueryDeptDto) {
    let { name = '' } = query;
    let entity = this.deptRepo.createQueryBuilder('dept');
    if (name) {
      entity.andWhere(`dept.name LIKE "%${name}%"`);
    }
    entity.skip(query.size * (query.page - 1)).take(query.size);
    const [list, total] = await entity.getManyAndCount();
    const treeData = ListToTree(list, (m: UpdateDeptDto) => m.id, (m: UpdateDeptDto) => m.name);
    return ResultData.ok({
      list: treeData,
      total,
      size: query.size,
      page: query.page
    })
  }

  //创建
  async create(createDeptDto: CreateDeptDto) {
    let { parentId } = createDeptDto;
    if (!parentId) {
      return ResultData.fail(500, '参数错误：缺少parentId');
    }
    let parent = await this.deptRepo.findOne({
      where: {
        id: parentId
      }
    })
    if (!parent && parentId != -1) {
      return ResultData.fail(500, '父级部门不存在');
    }
    await this.deptRepo.save(createDeptDto);
    return ResultData.ok();
  }

  //更新
  async update(updateDeptDto: UpdateDeptDto) {
    try {
      let { id, parentId, name } = updateDeptDto;
      if (!id || !parentId) {
        return ResultData.fail(500, "参数缺失");
      }
      let result = await this.deptRepo.findOne({
        where: { name, parentId }
      });
      if (result && result?.id != id) {
        return ResultData.fail(500, '部门名称已存在')
      }
      let entity = this.deptRepo.createQueryBuilder('dept');
      let parent = await this.deptRepo.findOne({
        where: {
          id: parentId
        }
      })
      if (!parent && parentId != -1) {
        return ResultData.fail(500, '父级部门不存在');
      }
      let count = await entity.where("dept.id=:id", { id }).getCount();
      if (!count) {
        return ResultData.fail(500, '更新的部门不存在');
      }
      let res = await this.deptRepo.update({ id }, updateDeptDto);
      if (res.affected) {
        return ResultData.ok('更新成功');
      } else {
        return ResultData.fail(500, '更新失败')
      }
    } catch (err) {
      return ResultData.fail(500, '更新失败' + err)
    }
  }

  //删除
  async remove(deptInfo: DeleteDeptDto) {
    let { ids } = deptInfo;
    if (!ids || ids.length == 0) {
      return ResultData.fail(500, '参数错误')
    }

    let involveIds = [];
    let involveCount = 0;
    for (let i = 0; i < ids.length; i++) {
      let id = ids[i];
      let data = await this.deptRepo.find({
        where: {
          parentId: id
        }
      });
      involveCount += data?.length;
      // if (data?.length) {
      //   data.map(item => {
      //     involveIds.push(item.id);
      //   })
      // }
    }
    if (involveCount) {
      return ResultData.fail(500, '删除的部门存在子部门')
    }
    let total = 0;
    let allIds = [...ids, ...involveIds];
    for (let i = 0; i < ids.length; i++) {
      let id = ids[i];
      let entity = this.userRepo.createQueryBuilder('user');
      entity.where("JSON_CONTAINS(user.deptIds,:deptId)", { deptId: id.toString() });
      let num = await entity.getCount();
      total += num;
    }
    if (total) {
      return ResultData.fail(500, '部门正在被使用')
    }
    await this.deptRepo.delete(ids);
    return ResultData.ok();
  }
}
